package com.webserver_v6.core;

import com.webserver_v6.controller.UserController;
import com.webserver_v6.http.HttpServletRequest;
import com.webserver_v6.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {

    private static DispatcherServlet instance = new DispatcherServlet();
    private static File rootDir;
    private static File staticDir;

    static {
        try {
            rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    private DispatcherServlet(){}

    public static DispatcherServlet getInstance(){
        return instance;
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getRequestURI();
        File file = new File(staticDir,path);
        if ("/regUser".equals(path)){
            UserController controller = new UserController();
            controller.reg(request,response);
        }else {
            if (file.isFile()){//根据用户提供的抽象路径去static目录下定位到一个文件
                response.setContentFile(file);

                response.addHeader("Server","BirdWebServer");
            }else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"/root/404.html");
                response.setContentFile(file);

            }
        }
    }
}
